//
//  InvitationAlearView.m
//  Exchange
//
//  Created by 张庆勇 on 2019/2/22.
//  Copyright © 2019年 张庆勇. All rights reserved.
//

#import "InvitationAlearView.h"
#define MainScreenRect [UIScreen mainScreen].bounds
@interface InvitationAlearView()
@property (nonatomic,strong)UIView *bgView;
@property (nonatomic,strong)UIImageView *invitationImageView;
@property (nonatomic,strong)UIImageView *qrcodeImage;
@property (nonatomic,strong)UIButton *saveButton;
@property (nonatomic,strong)NSString *imageurl;
@property (nonatomic,strong)NSString *QRcodWithUrl;
@property (nonatomic,strong)NSString *titleStr;
@end
@implementation InvitationAlearView

- (instancetype)initWithimageurl:(NSString *)imageurl
                        titleStr:(NSString *)titleStr
                    QRcodWithUrl:(NSString *)QRcodWithUrl
                       SaveBlock:(SaveBlock)saveBlock;
{
    
    if (self=[super init])
    {
        self.frame=MainScreenRect;
        self.backgroundColor=[UIColor colorWithWhite:.0 alpha:.6];
        self.userInteractionEnabled = YES;
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(dismiss)];
        [self addGestureRecognizer:tap];
        _imageurl = imageurl;
        _QRcodWithUrl = QRcodWithUrl;
        _titleStr = titleStr;
        [self addSubview:self.bgView];
        [_bgView addSubview:self.invitationImageView];
        [_invitationImageView addSubview:self.qrcodeImage];
        [_bgView addSubview:self.saveButton]; 
    }
    self.saveBlock=saveBlock;
    return self;
}
- (UIView *)bgView
{
    if (!_bgView) {
        _bgView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, RealValue_W(750)*0.7, RealValue_W(1334)*0.7 + RealValue_W(88))];
        _bgView.center =self.center;
        KViewRadius(_bgView, 4);
    }
    return _bgView;
}
- (UIImageView *)invitationImageView
{
    if (!_invitationImageView) {
        _invitationImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, _bgView.width, RealValue_W(1334)*0.7)];
        _invitationImageView.clipsToBounds = YES;
        _invitationImageView.contentMode             =UIViewContentModeScaleAspectFit;
        [_invitationImageView sd_setImageWithURL:[NSURL URLWithString:_imageurl]];
    }
    return _invitationImageView;
}
- (UIImageView *)qrcodeImage
{
    if (!_qrcodeImage) {
        _qrcodeImage = [[UIImageView alloc] initWithFrame:CGRectMake(0, _invitationImageView.height - RealValue_W(106) -8 , RealValue_W(106), RealValue_W(106))];
        _qrcodeImage.centerX = _invitationImageView.centerX;
        [self createQRcodWithUrl:_QRcodWithUrl qrcodeImageView:_qrcodeImage];/*生成二维码*/
    }
    return _qrcodeImage;
}
- (UIButton *)saveButton
{
    if (!_saveButton) {
        _saveButton = [[UIButton alloc] initWithFrame:CGRectMake(_invitationImageView.mj_x, _invitationImageView.bottom, _invitationImageView.width, RealValue_W(88))];
        _saveButton.backgroundColor = TABTITLECOLOR;
        [_saveButton setTitle:_titleStr forState:(UIControlStateNormal)];
        [_saveButton setTitleColor:WHITECOLOR forState:UIControlStateNormal];
        [_saveButton addTarget:self action:@selector(OKclick) forControlEvents:(UIControlEventTouchUpInside)];
        _saveButton.layer.masksToBounds     =YES;
        _saveButton.layer.cornerRadius      =2;
        _saveButton.titleLabel.font = AutoFont(15);
    }
    return _saveButton;
}
- (void)OKclick
{
    if (self.saveBlock)
    {
        self.saveBlock();
    }
    // 保存图片到相册
    UIImageWriteToSavedPhotosAlbum([self captureImageFromView:self.invitationImageView],self,@selector(imageSavedToPhotosAlbum:didFinishSavingWithError:contextInfo:),nil);
   
}
-(UIImage *)captureImageFromView:(UIView *)view{
    
    UIGraphicsBeginImageContextWithOptions(view.frame.size,NO, 0);
    
    [[UIColor clearColor] setFill];
    
    [[UIBezierPath bezierPathWithRect:view.bounds] fill];
    
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    
    [view.layer renderInContext:ctx];
    
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    
    UIGraphicsEndImageContext();
    
    return image;
    
}
#pragma mark 保存图片后的回调
- (void)imageSavedToPhotosAlbum:(UIImage*)image didFinishSavingWithError:  (NSError*)error contextInfo:(id)contextInfo
{
    NSString*message =@"";
    
    if(!error) {
        
        message =Localized(@"Asset_Saved_album");
        
        [EXUnit showSVProgressHUD:message];
        
    }else
    
    {
        
        message = [error description];
        [EXUnit showSVProgressHUD:Localized(@"album_message")];
        
    }
     [self dismissAlertView];
    
}
- (void)dismiss
{
    [self dismissAlertView];
}
-(void)dismissAlertView
{
    [self removeFromSuperview];
    
}
-(void)showLXAlertView
{
    [kWindow addSubview:self];
    [self setShowAnimation];
}
-(void)setShowAnimation{
    WeakSelf;
    switch (_animationStyle) {
        
        case LXASAnimationDefault:
        {
            [UIView animateWithDuration:0 delay:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
                [weakSelf.bgView.layer setValue:@(0) forKeyPath:@"transform.scale"];
            } completion:^(BOOL finished) {
                [UIView animateWithDuration:0.23 delay:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
                    [weakSelf.bgView.layer setValue:@(1.2) forKeyPath:@"transform.scale"];
                } completion:^(BOOL finished) {
                    [UIView animateWithDuration:0.09 delay:0.02 options:UIViewAnimationOptionCurveEaseInOut animations:^{
                        [weakSelf.bgView.layer setValue:@(.9) forKeyPath:@"transform.scale"];
                    } completion:^(BOOL finished) {
                        [UIView animateWithDuration:0.05 delay:0.02 options:UIViewAnimationOptionCurveEaseInOut animations:^{
                            [weakSelf.bgView.layer setValue:@(1.0) forKeyPath:@"transform.scale"];
                        } completion:^(BOOL finished) {
                            weakSelf.userInteractionEnabled = YES;
                        }];
                    }];
                }];
            }];
        }
        break;
        
        case LXASAnimationLeftShake:{
            
            CGPoint startPoint = CGPointMake(-_invitationImageView.width, self.center.y);
            weakSelf.bgView.layer.position=startPoint;
            
            //damping:阻尼，范围0-1，阻尼越接近于0，弹性效果越明显
            //velocity:弹性复位的速度
            [UIView animateWithDuration:.8 delay:0 usingSpringWithDamping:.5 initialSpringVelocity:1.0 options:UIViewAnimationOptionCurveEaseIn animations:^{
                weakSelf.bgView.layer.position=self.center;
                
            } completion:^(BOOL finished) {
                
            }];
        }
        break;
        
        case LXASAnimationTopShake:{
            
            CGPoint startPoint = CGPointMake(self.center.x, -_bgView.frame.size.height);
            _bgView.layer.position=startPoint;
            
            //damping:阻尼，范围0-1，阻尼越接近于0，弹性效果越明显
            //velocity:弹性复位的速度
            [UIView animateWithDuration:.8 delay:0 usingSpringWithDamping:.5 initialSpringVelocity:1.0 options:UIViewAnimationOptionCurveEaseIn animations:^{
                weakSelf.bgView.layer.position=self.center;
                
            } completion:^(BOOL finished) {
                
            }];
        }
        break;
        
        case LXASAnimationNO:{
            
        }
        
        break;
        
        default:
        break;
    }
}
- (void)createQRcodWithUrl:(NSString *)url qrcodeImageView:(UIImageView *)qrcodeImageView{
    // 1.创建过滤器
    
    CIFilter *filter = [CIFilter filterWithName:@"CIQRCodeGenerator"];
    
    // 2.恢复默认
    
    [filter setDefaults];
    
    // 3.给过滤器添加数据(正则表达式/账号和密码)
    
    //    NSString *dataString = @"http://www.520it.com";
    
    NSData *data = [url dataUsingEncoding:NSUTF8StringEncoding];
    
    [filter setValue:data forKeyPath:@"inputMessage"];
    
    // 4.获取输出的二维码
    
    CIImage *outputImage = [filter outputImage];
    
    // 5.将CIImage转换成UIImage，并放大显示
    
    qrcodeImageView.image = [self createNonInterpolatedUIImageFormCIImage:outputImage withSize:100];
    
}
/**
 
 * 根据CIImage生成指定大小的UIImage
 
 *
 
 * @param image CIImage
 
 * @param size 图片宽度
 
 */

- (UIImage *)createNonInterpolatedUIImageFormCIImage:(CIImage *)image withSize:(CGFloat) size

{
    
    CGRect extent = CGRectIntegral(image.extent);
    
    CGFloat scale = MIN(size/CGRectGetWidth(extent), size/CGRectGetHeight(extent));
    
    // 1.创建bitmap;
    
    size_t width = CGRectGetWidth(extent) * scale;
    
    size_t height = CGRectGetHeight(extent) * scale;
    
    CGColorSpaceRef cs = CGColorSpaceCreateDeviceGray();
    
    CGContextRef bitmapRef = CGBitmapContextCreate(nil, width, height, 8, 0, cs, (CGBitmapInfo)kCGImageAlphaNone);
    
    CIContext *context = [CIContext contextWithOptions:nil];
    
    CGImageRef bitmapImage = [context createCGImage:image fromRect:extent];
    
    CGContextSetInterpolationQuality(bitmapRef, kCGInterpolationNone);
    
    CGContextScaleCTM(bitmapRef, scale, scale);
    
    CGContextDrawImage(bitmapRef, extent, bitmapImage);
    
    // 2.保存bitmap到图片
    
    CGImageRef scaledImage = CGBitmapContextCreateImage(bitmapRef);
    
    CGContextRelease(bitmapRef);
    
    CGImageRelease(bitmapImage);
    
    return [UIImage imageWithCGImage:scaledImage];
    
}

@end
